import { useState, useEffect, useContext } from 'react';
import { NavBar, List, Button, InfiniteScroll, Toast } from 'antd-mobile';
import { UserAddOutline } from 'antd-mobile-icons';
import { useHistory } from 'react-router-dom';

import AvatarImage from '../../../components/AvatarImage';
import { MySdkStoreContext } from '../../../context';
import { NEW_APPLICATION_STORAGE_KEY } from '../../../constants';

import { NewFriendApplyStatus } from './config';

import './style.scss';

export default function() {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const [newFriendList, setNewFriendList] = useState([]);
  const [pagination, setPagination] = useState({});
  const [setting, setSetting] = useState({});
  const myUserId = mySdkStore.mockConfig.userId;

  const getFriendList = async (pageIndex) => {
    const { rows, totalPage } = await mySdkStore.sdk.queryFriendApplyListByStatus({ pageIndex: pageIndex || 1 });
    setNewFriendList(pageIndex === 1 ? rows : [...rows, ...newFriendList]);
    setPagination({ pageIndex, totalPage });
  }

  useEffect(() => {
    getFriendList(1);
  }, []);

  useEffect(async () => {
    const setting = await mySdkStore.sdk.querySecretConfig();
    setSetting(setting);
  }, []);

  useEffect(() => {
    const hasReadNewApplicationStr = localStorage.getItem(NEW_APPLICATION_STORAGE_KEY);
    let newApplicationObj = { hasReadNewFriendApplication: true };
    if (hasReadNewApplicationStr) {
      try {
        const hasReadNewApplicationObj = JSON.parse(hasReadNewApplicationStr);
        newApplicationObj = {...hasReadNewApplicationObj, hasReadNewFriendApplication: true };
      } catch {}
    }
    localStorage.setItem(NEW_APPLICATION_STORAGE_KEY, JSON.stringify(newApplicationObj));
  }, []);

  const getNextData = async () => {
    await getFriendList(pagination.pageIndex + 1);
  }

  const handlePassApply = async (toUserId, invitedNo) => {
    // todo: api 无请求 返回undefined
    const res = await mySdkStore.sdk.replyAddFriendRequest({ invitedNo, accept: true, toUserId });
    if (res?.errorMessage) {
      Toast.show(res?.errorMessage);
      return;
    }
    getFriendList(1);
  }

  const handleRefuse = async (toUserId, invitedNo) => {
    // todo: api 无请求 返回undefined
    const res = await mySdkStore.sdk.replyAddFriendRequest({ invitedNo, accept: false, toUserId });
    if (res?.errorMessage) {
      Toast.show(res?.errorMessage);
      return;
    }
    getFriendList(1);
  }

  const getExtra = (status: number | string, userInfo) => {
    if (userInfo.originnator !== myUserId && !setting?.secretConfig?.enableVerificationWhenAddMe) {
      return '已同意';
    }

    switch(status) {
      case NewFriendApplyStatus.WAITING:
        return userInfo.originnator === myUserId ? '等待中' : <>
          <Button size="mini" style={{ marginRight: 8 }} onClick={() => handleRefuse(userInfo.invitedUserId, userInfo.invitedNo)}>拒绝</Button>
          <Button size="mini" color="primary" onClick={() => handlePassApply(userInfo.invitedUserId, userInfo.invitedNo)}>同意</Button>
        </>
      case NewFriendApplyStatus.PASSED:
        return '已同意';
      case NewFriendApplyStatus.REFUSE:
        return '已拒绝';
      case NewFriendApplyStatus.EXPIRE:
        return '已过期';
    }
  }

  return (<div className="newFriendListPage">
      <NavBar
        onBack={() => history.goBack()}
        style={{ background: '#fff', border: 'none' }}
        right={<UserAddOutline style={{ color: 'rgba(0,0,0,0.65)', fontSize: 22 }} onClick={() => history.push({ pathname: '/addFriend' })} />}>
        新的朋友
      </NavBar>
      <List style={{ '--border-top': 0, '--border-bottom': 0, '--border-inner': 0, marginTop: 12 }}>
      { newFriendList.map((item) =>
          <List.Item
            key={item.id}
            prefix={<AvatarImage
              nickName={item.nickName}
              userName={item.userName}
              userId={item.invitedUserId}
              style={{ borderRadius: '8px' }}
              src={item.avatarUrl}
              width={42}
              height={42}
              fit='fill' />}
            description={<div className="userId">ID: {item.invitedUserId}</div>}
            extra={getExtra(item.status, item)}
            >
            <div className="userName">{ item.userName }</div>
          </List.Item>
      )}
    </List>
    <InfiniteScroll loadMore={getNextData} hasMore={pagination.pageIndex < pagination.totalPage} />
  </div>)
}